<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2020/7/1
 * Time: 14:38
 */

namespace app\commi\controller;

use think\Db;
use think\Request;

class Worker extends Base
{
    /**
     * 工作人员展示
     * @return mixed|\think\response\Json
     */
    public function index(){
        if(request()->isAjax ()){
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::name('committee_member')
                ->join('up_u_user', 'cm_match_user_id = user_id', 'left')
                ->where('cm_committee_id', session('com_id'))
                ->where('cm_member_type', 'NEQ', 1)
                ->count();// 获取总条数
            $lists = Db::name('committee_member')
                ->join('up_u_user', 'cm_match_user_id = user_id', 'left')
                ->field('cm_id, user_username, user_real_name, cm_member_type, user_create_id, 
                user_phone, cm_time, cm_login_ID')
                ->where('cm_committee_id', session('com_id'))
                ->where('cm_member_type', 'NEQ', 1)
                ->page($Nowpage, $limits)
                ->order('cm_time desc')
                ->select();
        
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        
        return $this->fetch();
    }
    
    /**
     * 添加工作人员
     * @return mixed|\think\response\Json
     */
    public function workerAdd(){
        if(Request::instance()->isPost()){
            $cm_member_type = input('cm_member_type');
            $cm_match_user_id = input('cm_match_user_id');
            $cm_login_ID = trim(input('cm_login_ID'), ' ');
            $cm_login_pwd = trim(input('cm_login_pwd'), ' ');
            $md5_pwd = md5($cm_login_pwd);
            $is_have = Db::table('up_committee_member')
                ->where('cm_login_ID', $cm_login_ID)
                ->where('cm_login_pwd', $md5_pwd)
                ->find();
            if($is_have){
                return json(['code' => 100, 'msg' => '账号密码重复']);
            }
            
            $match = Db::table('up_match')
                ->where('match_committee_id', session('com_id'))
                ->where('match_member_id', session('cm_id'))
                ->field('match_cate, match_zong_user_id, match_zhong_user_id, 
                match_bianpai_user_id, match_zhuren_user_id, match_mishu_user_id, 
                match_hexiao_user_id, match_start_time, match_id')
                ->find();
            if(!$match){
                return json(['code' => 100, 'msg' => '请先创建赛事']);
            }
            
            $is_choose = Db::table('up_committee_member')
                ->join('up_match', 'cm_match_id = match_id', 'left')
                ->where('cm_match_user_id', $cm_match_user_id)
//                ->where('match_end_time', '>', $match['match_start_time'])
                ->where('match_id', 'NEQ', $match['match_id'])
                ->where('match_status', 'IN', '1,2')
                ->find();
            if($is_choose){
                return json(['code' => 100, 'msg' => '该用户已被选择其他赛事']);
            }
            
            if($cm_member_type == 2){
                // 总裁判只能添加一个
                $have_zong = Db::table('up_committee_member')
                    ->where('cm_match_id', $match['match_id'])
                    ->where('cm_member_type', 2)
                    ->find();
                if($have_zong){
                    return json(['code' => 100, 'msg' => '已添加过总裁判']);
                }
                // 如果是总裁判，判断被添加用户是否已经被添加过，无论是其他角色还是总裁判
                $other_role = Db::table('up_committee_member')
                    ->where('cm_match_id', $match['match_id'])
                    ->where('cm_match_user_id', $cm_match_user_id)
                    ->find();
                if($other_role){
                    return json(['code' => 100, 'msg' => '该用户已添加过']);
                }
            }else{
                // 如果不是总裁判，需要判断被添加用户是不是已经被添加成总裁判
                $zong_role = Db::table('up_committee_member')
                    ->where('cm_match_id', $match['match_id'])
                    ->where('cm_match_user_id', $cm_match_user_id)
                    ->where('cm_member_type', 2)
                    ->find();
                if($zong_role){
                    return json(['code' => 100, 'msg' => '该用户已经是总裁判']);
                }
            }
    
            // 相同的人被添加到本场比赛的相同角色
            $exist = Db::table('up_committee_member')
                ->where('cm_match_user_id', $cm_match_user_id)
                ->where('cm_match_id', $match['match_id'])
                ->where('cm_member_type', $cm_member_type)
                ->find();
            if($exist){
                return json(['code' => 100, 'msg' => '请不要重复添加']);
            }
            
            if($cm_member_type == 2){
                $field = 'match_zong_user_id';
                $user_id = $cm_match_user_id;
            }elseif($cm_member_type == 3){
                $field = 'match_zhong_user_id';
                if(empty($match['match_zhong_user_id'])){
                    $user_id = ',' . $cm_match_user_id . ',';
                }else{
                    $user_id = $match['match_zhong_user_id'] . $cm_match_user_id . ',';
                }
            }elseif($cm_member_type == 4){
                $field = 'match_bianpai_user_id';
                if(empty($match['match_bianpai_user_id'])){
                    $user_id = ',' . $cm_match_user_id . ',';
                }else{
                    $user_id = $match['match_bianpai_user_id'] . $cm_match_user_id . ',';
                }
            }elseif($cm_member_type == 5){
                $field = 'match_zhuren_user_id';
                if(empty($match['match_zhuren_user_id'])){
                    $user_id = ',' . $cm_match_user_id . ',';
                }else{
                    $user_id = $match['match_zhuren_user_id'] . $cm_match_user_id . ',';
                }
            }elseif($cm_member_type == 6){
                $field = 'match_mishu_user_id';
                if(empty($match['match_mishu_user_id'])){
                    $user_id = ',' . $cm_match_user_id . ',';
                }else{
                    $user_id = $match['match_mishu_user_id'] . $cm_match_user_id . ',';
                }
            }else{
                $field = 'match_hexiao_user_id';
                if(empty($match['match_hexiao_user_id'])){
                    $user_id = ',' . $cm_match_user_id . ',';
                }else{
                    $user_id = $match['match_hexiao_user_id'] . $cm_match_user_id . ',';
                }
            }
            
            $insert = [
                'cm_committee_id' => session('com_id'),
                'cm_login_ID' => $cm_login_ID,
                'cm_login_pwd' => $md5_pwd,
                'cm_member_role' => $match['match_cate'],
                'cm_member_type' => $cm_member_type,
                'cm_match_id' => $match['match_id'],
                'cm_match_user_id' => $cm_match_user_id,
                'cm_time' => date('Y-m-d H:i:s')
            ];
            
            Db::startTrans();
            try{
                // 组委会管理人员
                Db::table('up_committee_member')->insert($insert);
                // 比赛表
                Db::table('up_match')->where('match_id', $match['match_id'])->update([$field => $user_id]);
                Db::commit();
                return json(['code' => 200, 'msg' => '添加成功']);
            }catch(\Exception $e){
                Db::rollback();
                return json(['code' => 100, 'msg' => '添加失败']);
            }
        }
        $user = Db::table('up_u_user')
            ->where('user_status', 1)
            ->field('user_id, user_username, user_phone, user_create_id')
            ->select();
        $this->assign([
            'user' => $user
        ]);
        $lose = $this->lostTime();
        if($lose == 1){
            return $this->fetch('/lose');
        }else{
            return $this->fetch('worker/workeradd');
        }
    }
    
    /**
     * 编辑员工
     * @return mixed|\think\response\Json
     */
    public function workerEdit(){
        $cm_id = input('cm_id');
        if(Request::instance()->isPost()){
            $cm_member_type = input('cm_member_type');
            $cm_match_user_id = input('cm_match_user_id');
            $cm_login_ID = trim(input('cm_login_ID'), ' ');
            $cm_login_pwd = trim(input('cm_login_pwd'), ' ');
            $mem = Db::table('up_committee_member')
                ->field('cm_login_ID, cm_member_type, cm_match_user_id, cm_login_pwd')
                ->where('cm_id', $cm_id)
                ->find();
            if(empty($cm_login_pwd)){
                $is_have = Db::table('up_committee_member')
                    ->where('cm_login_ID', $cm_login_ID)
                    ->where('cm_login_pwd', $mem['cm_login_pwd'])
                    ->where('cm_id', 'NEQ', $cm_id)
                    ->find();
            }else{
                $md5_pwd = md5($cm_login_pwd);
                $is_have = Db::table('up_committee_member')
                    ->where('cm_login_ID', $cm_login_ID)
                    ->where('cm_login_pwd', $md5_pwd)
                    ->where('cm_id', 'NEQ', $cm_id)
                    ->find();
            }
            if($is_have){
                return json(['code' => 100, 'msg' => '账号密码重复']);
            }
    
            $match = Db::table('up_match')
                ->where('match_committee_id', session('com_id'))
                ->where('match_member_id', session('cm_id'))
                ->field('match_cate, match_zong_user_id, match_zhong_user_id, 
                match_bianpai_user_id, match_zhuren_user_id, match_mishu_user_id, 
                match_hexiao_user_id, match_start_time, match_id')
                ->find();
            if(!$match){
                return json(['code' => 100, 'msg' => '请先创建赛事']);
            }
    
            $is_choose = Db::table('up_committee_member')
                ->join('up_match', 'cm_match_id = match_id', 'left')
                ->where('cm_match_user_id', $cm_match_user_id)
//                ->where('match_end_time', '>', $match['match_start_time'])
                ->where('match_status', 'IN', '1,2')
                ->where('match_id', 'NEQ', $match['match_id'])
                ->find();
            if($is_choose){
                return json(['code' => 100, 'msg' => '该用户已被选择其他赛事']);
            }
    
            if($cm_member_type == 2){
                // 总裁判只能添加一个
                $have_zong = Db::table('up_committee_member')
                    ->where('cm_match_id', $match['match_id'])
                    ->where('cm_member_type', 2)
                    ->where('cm_id', 'NEQ', $cm_id)
                    ->find();
                if($have_zong){
                    return json(['code' => 100, 'msg' => '已添加过总裁判']);
                }
                // 如果是总裁判，判断被添加用户是否已经被添加过，无论是其他角色还是总裁判
                $other_role = Db::table('up_committee_member')
                    ->where('cm_match_id', $match['match_id'])
                    ->where('cm_match_user_id', $cm_match_user_id)
                    ->where('cm_id', 'NEQ', $cm_id)
                    ->find();
                if($other_role){
                    return json(['code' => 100, 'msg' => '该用户已添加过']);
                }
            }else{
                // 如果不是总裁判，需要判断被添加用户是不是已经被添加成总裁判
                $zong_role = Db::table('up_committee_member')
                    ->where('cm_match_id', $match['match_id'])
                    ->where('cm_match_user_id', $cm_match_user_id)
                    ->where('cm_id', 'NEQ', $cm_id)
                    ->where('cm_member_type', 2)
                    ->find();
                if($zong_role){
                    return json(['code' => 100, 'msg' => '该用户已经是总裁判']);
                }
            }
    
            $exist = Db::table('up_committee_member')
                ->where('cm_match_user_id', $cm_match_user_id)
                ->where('cm_match_id', $match['match_id'])
                ->where('cm_member_type', $cm_member_type)
                ->where('cm_id', 'NEQ', $cm_id)
                ->find();
            if($exist){
                return json(['code' => 100, 'msg' => '请不要重复添加']);
            }
    
            if($cm_member_type == 2){
                $field = 'match_zong_user_id';
                $user_id = $cm_match_user_id;
            }elseif($cm_member_type == 3){
                $field = 'match_zhong_user_id';
                $ids = trim($match['match_zhong_user_id'], ',');
                $ids_arr = explode(',', $ids);
                $new_arr = array_diff($ids_arr, [$mem['cm_match_user_id']]);
                $user_id = ',' . implode(',', $new_arr) . ',' . $cm_match_user_id . ',';
            }elseif($cm_member_type == 4){
                $field = 'match_bianpai_user_id';
                $ids = trim($match['match_bianpai_user_id'], ',');
                $ids_arr = explode(',', $ids);
                $new_arr = array_diff($ids_arr, [$mem['cm_match_user_id']]);
                $user_id = ',' . implode(',', $new_arr) . ',' . $cm_match_user_id . ',';
            }elseif($cm_member_type == 5){
                $field = 'match_zhuren_user_id';
                $ids = trim($match['match_zhuren_user_id'], ',');
                $ids_arr = explode(',', $ids);
                $new_arr = array_diff($ids_arr, [$mem['cm_match_user_id']]);
                $user_id = ',' . implode(',', $new_arr) . ',' . $cm_match_user_id . ',';
            }elseif($cm_member_type == 6){
                $field = 'match_mishu_user_id';
                $ids = trim($match['match_mishu_user_id'], ',');
                $ids_arr = explode(',', $ids);
                $new_arr = array_diff($ids_arr, [$mem['cm_match_user_id']]);
                $user_id = ',' . implode(',', $new_arr) . ',' . $cm_match_user_id . ',';
            }else{
                $field = 'match_hexiao_user_id';
                $ids = trim($match['match_hexiao_user_id'], ',');
                $ids_arr = explode(',', $ids);
                $new_arr = array_diff($ids_arr, [$mem['cm_match_user_id']]);
                $user_id = ',' . implode(',', $new_arr) . ',' . $cm_match_user_id . ',';
            }
    
            $update = [
                'cm_login_ID' => $cm_login_ID,
                'cm_member_type' => $cm_member_type,
                'cm_match_user_id' => $cm_match_user_id
            ];
            if(!empty($cm_login_pwd)){
                $update['cm_login_pwd'] = md5($cm_login_pwd);
            }
    
            Db::startTrans();
            try{
                // 组委会管理人员
                Db::table('up_committee_member')->where('cm_id', $cm_id)->update($update);
                // 比赛表
                Db::table('up_match')->where('match_id', $match['match_id'])->update([$field => $user_id]);
                Db::commit();
                return json(['code' => 200, 'msg' => '编辑成功']);
            }catch(\Exception $e){
                Db::rollback();
                return json(['code' => 100, 'msg' => '编辑失败']);
            }
            
        }
        $member = Db::table('up_committee_member')
            ->field('cm_login_ID, cm_member_type, cm_match_user_id')
            ->where('cm_id', $cm_id)
            ->find();
        $user = Db::table('up_u_user')
            ->where('user_status', 1)
            ->field('user_id, user_username, user_phone, user_create_id')
            ->select();
        $this->assign([
            'member' => $member,
            'user' => $user,
            'cm_id' => $cm_id
        ]);
        $lose = $this->lostTime();
        if($lose == 1){
            return $this->fetch('/lose');
        }else{
            return $this->fetch('worker/workeredit');
        }
    }
    
    /**
     * 删除员工
     * @return \think\response\Json
     */
    public function workerDel(){
        $lose = $this->lostTime();
        if($lose == 1){
            return json(['code' => 100, 'msg' => '账号已过期，非法操作']);
        }
        $cm_id = input('id');
        $member = Db::table('up_committee_member')
            ->join('up_match', 'cm_match_id = match_id', 'left')
            ->where('cm_id', $cm_id)
            ->field('cm_match_id, cm_match_user_id, cm_member_type, match_zhong_user_id, match_bianpai_user_id, 
            match_zhuren_user_id, match_mishu_user_id, match_hexiao_user_id')
            ->find();
        if($member['cm_member_type'] == 2){
            $field = 'match_zong_user_id';
            $user_id = null;
        }elseif($member['cm_member_type'] == 3){
            $field = 'match_zhong_user_id';
            $ids = trim($member['match_zhong_user_id'], ',');
            $ids_arr = explode(',', $ids);
            $new_arr = array_diff($ids_arr, [$member['cm_match_user_id']]);
            if(!$ids_arr){
                $user_id = ',' . implode(',', $new_arr) . ',';
            }else{
                $user_id = null;
            }
        }elseif($member['cm_member_type'] == 4){
            $field = 'match_bianpai_user_id';
            $ids = trim($member['match_bianpai_user_id'], ',');
            $ids_arr = explode(',', $ids);
            $new_arr = array_diff($ids_arr, [$member['cm_match_user_id']]);
            if(!$ids_arr){
                $user_id = ',' . implode(',', $new_arr) . ',';
            }else{
                $user_id = null;
            }
        }elseif($member['cm_member_type'] == 5){
            $field = 'match_zhuren_user_id';
            $ids = trim($member['match_zhuren_user_id'], ',');
            $ids_arr = explode(',', $ids);
            $new_arr = array_diff($ids_arr, [$member['cm_match_user_id']]);
            if(!$ids_arr){
                $user_id = ',' . implode(',', $new_arr) . ',';
            }else{
                $user_id = null;
            }
        }elseif($member['cm_member_type'] == 6){
            $field = 'match_mishu_user_id';
            $ids = trim($member['match_mishu_user_id'], ',');
            $ids_arr = explode(',', $ids);
            $new_arr = array_diff($ids_arr, [$member['cm_match_user_id']]);
            if(!$ids_arr){
                $user_id = ',' . implode(',', $new_arr) . ',';
            }else{
                $user_id = null;
            }
        }else{
            $field = 'match_hexiao_user_id';
            $ids = trim($member['match_hexiao_user_id'], ',');
            $ids_arr = explode(',', $ids);
            $new_arr = array_diff($ids_arr, [$member['cm_match_user_id']]);
            if(!$ids_arr){
                $user_id = ',' . implode(',', $new_arr) . ',';
            }else{
                $user_id = null;
            }
        }
        Db::startTrans();
        try{
            // 删除
            Db::table('up_committee_member')->delete($cm_id);
            // 比赛
            Db::table('up_match')->where('match_id', $member['cm_match_id'])->update([$field => $user_id]);
            Db::commit();
            return json(['code' => 200, 'msg' => '删除成功']);
        }catch(\Exception $e){
            Db::rollback();
            return json(['code' => 100, 'msg' => '删除失败']);
        }
    }
}